/**
 * 模拟API服务
 * 处理模拟API请求
 */

const storage = require('../storage');

// 模拟数据常量
const DEFAULT_AVATAR = '/images/avatar/default.png';

// 处理请求
function process(endpoint, method, data) {
  console.log(`[Mock] 处理请求: ${method} ${endpoint}`, data);
  
  // 根据端点分发到不同的处理函数
  if (endpoint.startsWith('/user')) {
    return handleUserRequests(endpoint, method, data);
  } else if (endpoint.startsWith('/medical-history')) {
    return handleMedicalHistoryRequests(endpoint, method, data);
  } else if (endpoint.startsWith('/health-targets')) {
    return handleHealthTargetsRequests(endpoint, method, data);
  } else if (endpoint.startsWith('/risk-assessment')) {
    return handleRiskAssessmentRequests(endpoint, method, data);
  }
  
  // 未实现的API端点
  return {
    error: true,
    code: 404,
    message: `未实现的API端点: ${method} ${endpoint}`
  };
}

/**
 * 处理用户相关的请求
 */
function handleUserRequests(endpoint, method, data) {
  // 微信登录
  if (endpoint === '/user/wx-login' && method === 'POST') {
    return mockWxLogin(data);
  }
  
  // 获取用户信息
  if (endpoint === '/user/profile' && method === 'GET') {
    return mockGetUserProfile();
  }
  
  // 更新用户信息
  if (endpoint === '/user/profile' && method === 'PUT') {
    return mockUpdateUserProfile(data);
  }
  
  // 解密手机号
  if (endpoint === '/user/decrypt-phone' && method === 'POST') {
    return mockDecryptPhone(data);
  }
  
  // 获取用户风险等级
  if (endpoint === '/user/risk-level' && method === 'GET') {
    return mockGetUserRiskLevel();
  }
  
  // 用户退出登录
  if (endpoint === '/user/logout' && method === 'POST') {
    return mockLogout();
  }
  
  return { error: true, code: 404, message: '未实现的用户API' };
}

/**
 * 处理医疗病史相关的请求
 */
function handleMedicalHistoryRequests(endpoint, method, data) {
  // 获取所有病史
  if (endpoint === '/medical-history' && method === 'GET') {
    return mockGetMedicalHistory();
  }
  
  // 添加病史
  if (endpoint === '/medical-history' && method === 'POST') {
    return mockAddMedicalHistory(data);
  }
  
  // 检查是否是编辑/删除特定ID的记录
  const idMatch = endpoint.match(/\/medical-history\/([^\/]+)$/);
  if (idMatch) {
    const id = idMatch[1];
    
    // 获取单条病史
    if (method === 'GET') {
      return mockGetMedicalHistoryById(id);
    }
    
    // 更新病史
    if (method === 'PUT') {
      return mockUpdateMedicalHistory(id, data);
    }
    
    // 删除病史
    if (method === 'DELETE') {
      return mockDeleteMedicalHistory(id);
    }
  }
  
  return { error: true, code: 404, message: '未实现的病史API' };
}

/**
 * 处理健康目标相关的请求
 */
function handleHealthTargetsRequests(endpoint, method, data) {
  // 获取所有健康目标
  if (endpoint === '/health-targets' && method === 'GET') {
    return mockGetHealthTargets();
  }
  
  // 添加健康目标
  if (endpoint === '/health-targets' && method === 'POST') {
    return mockAddHealthTarget(data);
  }
  
  // 检查是否是编辑/删除特定ID的记录
  const idMatch = endpoint.match(/\/health-targets\/([^\/]+)$/);
  if (idMatch) {
    const id = idMatch[1];
    
    // 获取单条健康目标
    if (method === 'GET') {
      return mockGetHealthTargetById(id);
    }
    
    // 更新健康目标
    if (method === 'PUT') {
      return mockUpdateHealthTarget(id, data);
    }
    
    // 删除健康目标
    if (method === 'DELETE') {
      return mockDeleteHealthTarget(id);
    }
  }
  
  return { error: true, code: 404, message: '未实现的健康目标API' };
}

/**
 * 处理风险评估相关的请求
 */
function handleRiskAssessmentRequests(endpoint, method, data) {
  // 获取风险评估
  if (endpoint === '/risk-assessment' && method === 'GET') {
    return mockGetRiskAssessment();
  }
  
  // 计算风险评估
  if (endpoint === '/risk-assessment/calculate' && method === 'POST') {
    return mockCalculateRiskAssessment(data);
  }
  
  return { error: true, code: 404, message: '未实现的风险评估API' };
}

/**
 * 模拟微信登录
 */
function mockWxLogin(data) {
  const { code, userInfo } = data;
  
  // 生成随机openid
  const openid = 'openid_' + Math.random().toString(36).substr(2, 9);
  
  // 创建用户记录
  const user = {
    id: 'user_' + Math.random().toString(36).substr(2, 9),
    openid,
    nickName: userInfo.nickName || '微信用户',
    avatarUrl: userInfo.avatarUrl || DEFAULT_AVATAR,
    gender: userInfo.gender === 1 ? '男' : (userInfo.gender === 2 ? '女' : '未知'),
    createdAt: new Date().toISOString()
  };
  
  // 检查是否已有用户信息，有则合并
  const existingUser = storage.db.user.getCurrentUser();
  const mergedUser = existingUser ? { ...existingUser, ...user } : user;
  
  // 保存用户信息
  storage.db.user.setCurrentUser(mergedUser);
  
  // 生成token
  const token = 'wx_token_' + Math.random().toString(36).substr(2, 9);
  storage.db.user.setToken(token);
  
  // 判断是否需要完善资料
  const needCompleteProfile = !mergedUser.height || !mergedUser.weight || !mergedUser.birthDate;
  
  return {
    success: true,
    code: 200,
    data: {
      user: mergedUser,
      token,
      needCompleteProfile
    }
  };
}

/**
 * 模拟获取用户信息
 */
function mockGetUserProfile() {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  return {
    success: true,
    code: 200,
    data: user
  };
}

/**
 * 模拟更新用户信息
 */
function mockUpdateUserProfile(data) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  // 更新用户信息
  const updatedUser = {
    ...user,
    ...data,
    updatedAt: new Date().toISOString()
  };
  
  // 保存更新后的用户信息
  storage.db.user.setCurrentUser(updatedUser);
  
  return {
    success: true,
    code: 200,
    data: updatedUser
  };
}

/**
 * 模拟解密手机号
 */
function mockDecryptPhone(data) {
  // 生成随机手机号
  const phoneNumber = '1' + Math.floor(Math.random() * 9 + 3) + 
                     Math.random().toString().substr(2, 9).padStart(9, '0');
  
  return {
    success: true,
    code: 200,
    data: {
      phoneNumber
    }
  };
}

/**
 * 模拟获取用户风险等级
 */
function mockGetUserRiskLevel() {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  // 计算风险等级
  const riskLevel = calculateUserRiskLevel(user);
  
  return {
    success: true,
    code: 200,
    data: riskLevel
  };
}

/**
 * 模拟退出登录
 */
function mockLogout() {
  storage.db.user.clearCurrentUser();
  storage.db.user.clearToken();
  
  return {
    success: true,
    code: 200,
    message: '退出登录成功'
  };
}

/**
 * 计算用户风险等级
 */
function calculateUserRiskLevel(user) {
  // 风险分数初始值
  let riskScore = 50;
  
  // 根据用户信息计算风险得分
  // 1. 年龄因素
  if (user.age) {
    if (user.age >= 65) riskScore += 20;
    else if (user.age >= 45) riskScore += 10;
    else if (user.age >= 35) riskScore += 5;
  }
  
  // 2. BMI因素
  if (user.height && user.weight) {
    const heightInMeters = user.height / 100;
    const bmi = user.weight / (heightInMeters * heightInMeters);
    
    if (bmi >= 30) riskScore += 20;
    else if (bmi >= 28) riskScore += 15;
    else if (bmi >= 25) riskScore += 10;
    else if (bmi <= 18.5) riskScore += 5;
  }
  
  // 3. 家族史因素
  if (user.familyHistory) {
    if (user.familyHistory.includes('糖尿病')) riskScore += 15;
    if (user.familyHistory.includes('高血压')) riskScore += 10;
    if (user.familyHistory.includes('心脏病')) riskScore += 10;
  }
  
  // 4. 生活习惯因素
  if (user.isSmoking) riskScore += 10;
  if (user.drinkingFrequency === 'frequent') riskScore += 10;
  if (user.drinkingFrequency === 'moderate') riskScore += 5;
  
  // 确定风险等级
  let riskLevel;
  if (riskScore >= 80) riskLevel = 'high';
  else if (riskScore >= 60) riskLevel = 'medium';
  else riskLevel = 'low';
  
  return {
    score: riskScore,
    level: riskLevel,
    levelText: riskLevel === 'high' ? '高风险' : (riskLevel === 'medium' ? '中风险' : '低风险'),
    factors: generateRiskFactors(user),
    recommendations: generateRecommendations(riskLevel)
  };
}

/**
 * 生成风险因素说明
 */
function generateRiskFactors(user) {
  const factors = [];
  
  if (user.age && user.age >= 45) factors.push('年龄≥45岁');
  
  if (user.height && user.weight) {
    const heightInMeters = user.height / 100;
    const bmi = user.weight / (heightInMeters * heightInMeters);
    if (bmi >= 25) factors.push(`BMI指数≥25 (${bmi.toFixed(1)})`);
  }
  
  if (user.familyHistory) {
    if (user.familyHistory.includes('糖尿病')) factors.push('糖尿病家族史');
    if (user.familyHistory.includes('高血压')) factors.push('高血压家族史');
    if (user.familyHistory.includes('心脏病')) factors.push('心脏病家族史');
  }
  
  if (user.isSmoking) factors.push('吸烟');
  if (user.drinkingFrequency === 'frequent') factors.push('频繁饮酒');
  
  return factors;
}

/**
 * 生成健康建议
 */
function generateRecommendations(riskLevel) {
  const baseRecommendations = [
    '保持健康饮食，控制总热量摄入',
    '每周进行150分钟中等强度有氧运动',
    '保持充足的睡眠'
  ];
  
  if (riskLevel === 'high') {
    return [
      ...baseRecommendations,
      '每日监测血糖',
      '定期进行糖化血红蛋白检查',
      '控制碳水化合物摄入',
      '建议咨询医生进行专业评估'
    ];
  } else if (riskLevel === 'medium') {
    return [
      ...baseRecommendations,
      '每周监测血糖2-3次',
      '控制体重',
      '限制糖类摄入'
    ];
  } else {
    return [
      ...baseRecommendations,
      '每月进行一次血糖检测',
      '保持健康生活方式'
    ];
  }
}

/**
 * 模拟获取医疗病史列表
 */
function mockGetMedicalHistory() {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const records = storage.db.medicalHistory.getAll();
  
  return {
    success: true,
    code: 200,
    data: records
  };
}

/**
 * 模拟添加医疗病史
 */
function mockAddMedicalHistory(data) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const newRecord = storage.db.medicalHistory.add({
    ...data,
    userId: user.id
  });
  
  return {
    success: true,
    code: 201,
    data: newRecord
  };
}

/**
 * 模拟获取单条医疗病史
 */
function mockGetMedicalHistoryById(id) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const record = storage.db.medicalHistory.getById(id);
  
  if (!record) {
    return {
      error: true,
      code: 404,
      message: '病史记录不存在'
    };
  }
  
  return {
    success: true,
    code: 200,
    data: record
  };
}

/**
 * 模拟更新医疗病史
 */
function mockUpdateMedicalHistory(id, data) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const updatedRecord = storage.db.medicalHistory.update(id, data);
  
  if (!updatedRecord) {
    return {
      error: true,
      code: 404,
      message: '病史记录不存在'
    };
  }
  
  return {
    success: true,
    code: 200,
    data: updatedRecord
  };
}

/**
 * 模拟删除医疗病史
 */
function mockDeleteMedicalHistory(id) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const success = storage.db.medicalHistory.delete(id);
  
  if (!success) {
    return {
      error: true,
      code: 404,
      message: '病史记录不存在'
    };
  }
  
  return {
    success: true,
    code: 200,
    message: '删除成功'
  };
}

/**
 * 模拟获取健康目标列表
 */
function mockGetHealthTargets() {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const targets = storage.db.healthTargets.getAll();
  
  return {
    success: true,
    code: 200,
    data: targets
  };
}

/**
 * 模拟添加健康目标
 */
function mockAddHealthTarget(data) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const newTarget = storage.db.healthTargets.add({
    ...data,
    userId: user.id
  });
  
  return {
    success: true,
    code: 201,
    data: newTarget
  };
}

/**
 * 模拟获取单条健康目标
 */
function mockGetHealthTargetById(id) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const target = storage.db.healthTargets.getById(id);
  
  if (!target) {
    return {
      error: true,
      code: 404,
      message: '健康目标不存在'
    };
  }
  
  return {
    success: true,
    code: 200,
    data: target
  };
}

/**
 * 模拟更新健康目标
 */
function mockUpdateHealthTarget(id, data) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const updatedTarget = storage.db.healthTargets.update(id, data);
  
  if (!updatedTarget) {
    return {
      error: true,
      code: 404,
      message: '健康目标不存在'
    };
  }
  
  return {
    success: true,
    code: 200,
    data: updatedTarget
  };
}

/**
 * 模拟删除健康目标
 */
function mockDeleteHealthTarget(id) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const success = storage.db.healthTargets.delete(id);
  
  if (!success) {
    return {
      error: true,
      code: 404,
      message: '健康目标不存在'
    };
  }
  
  return {
    success: true,
    code: 200,
    message: '删除成功'
  };
}

/**
 * 模拟获取风险评估
 */
function mockGetRiskAssessment() {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  const riskAssessment = calculateUserRiskLevel(user);
  
  return {
    success: true,
    code: 200,
    data: {
      ...riskAssessment,
      lastUpdateTime: new Date().toISOString()
    }
  };
}

/**
 * 模拟计算风险评估
 */
function mockCalculateRiskAssessment(data) {
  const user = storage.db.user.getCurrentUser();
  
  if (!user) {
    return {
      error: true,
      code: 401,
      message: '用户未登录'
    };
  }
  
  // 合并提供的数据和用户数据进行风险评估
  const mergedData = { ...user, ...data };
  const riskAssessment = calculateUserRiskLevel(mergedData);
  
  return {
    success: true,
    code: 200,
    data: {
      ...riskAssessment,
      lastUpdateTime: new Date().toISOString()
    }
  };
}

// 导出模块
module.exports = {
  process
}; 